<template>
  <el-dialog
    v-model="dialogVisible"
    :title="
      certificate
        ? $t('pageCertificates.replaceCertificate')
        : $t('pageCertificates.addNewCertificate')
    "
    width="500"
    @close="resetForm()"
  >
    <el-form
      ref="uploadCertificateFormRef"
      :model="form"
      :rules="rules"
      label-position="top"
    >
      <!-- Replace Certificate type -->
      <template v-if="certificate !== null">
        <span>{{ $t('pageCertificates.modal.certificateType') }}</span>
        <div>{{ certificate?.certificate }}</div>
      </template>

      <!-- Add new Certificate type -->
      <el-form-item
        :label="$t('pageCertificates.modal.certificateType')"
        prop="certificateType"
        v-else
      >
        <el-select
          v-model="form.certificateType"
          placeholder="Select"
          style="width: 100%"
        >
          <el-option
            v-for="item in certificateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="$t('pageCertificates.modal.certificateFile')"
        prop="file"
      >
        <el-upload
          v-model:file-list="form.file"
          :limit="1"
          ref="uploadRef"
          :auto-upload="false"
          style="width: 100%"
        >
          <template #trigger>
            <el-button type="primary">
              {{ $t('global.fileUpload.browseText') }}
            </el-button>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">
          {{ $t('global.action.cancel') }}
        </el-button>
        <el-button type="primary" @click="onOk" v-if="certificate">
          {{ $t('global.action.replace') }}
        </el-button>
        <el-button type="primary" @click="onOk" v-else>
          {{ $t('global.action.add') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import useVuelidateTool from '@/hooks/useVuelidateTool';
import { useCertificatesStore } from '@/store/UserSecurity/Certificates/CertificatesStore';

const CertificatesStore = useCertificatesStore();
const { useVuelidate, required, requiredIf, elementInputValidator } =
  useVuelidateTool();

const dialogVisible = ref(false);
const uploadCertificateFormRef = ref();

const form = reactive({ certificateType: '' as number | string, file: [] });

const certificateTypes = computed(() => CertificatesStore.availableUploadTypes);

const certificateOptions = computed(() => {
  return certificateTypes.value.map(
    ({ type, label }: { type: string; label: string }) => {
      return {
        text: label,
        value: type,
      };
    },
  );
});

// Set vuelidate rules.
const v$ = useVuelidate(
  {
    certificateType: {
      required: requiredIf(function () {
        return !props.certificate;
      }),
    },
    file: {
      required,
    },
  },
  form,
);

// validators
const rules = computed(() => {
  return {
    certificateType: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'certificateType'),
      },
    ],
    file: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'file'),
      },
    ],
  };
});

const onOk = async () => {
  v$.value.$touch();
  if (v$.value.$invalid) return;
  closeModal();

  let certificate = props.certificate;
  emit('ok', {
    addNew: !certificate,
    certificateType: form.certificateType,
    file: form.file[0],
    location: certificate ? certificate?.location : null,
    type: certificate ? certificate.type : form.certificateType,
  });
};

const resetForm = () => {
  uploadCertificateFormRef.value?.resetFields();
};

const closeModal = () => {
  nextTick(() => {
    dialogVisible.value = false;
  });
};

const props = defineProps({
  certificate: Object,
});
defineExpose({
  dialogVisible,
});
const emit = defineEmits(['ok']);

watch(certificateOptions, function (options: { value: number }[]) {
  if (options.length) {
    form.certificateType = options[0].value;
  }
});
</script>

<style lang="scss" scoped></style>
